package com.example.admin.goodnews.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.admin.goodnews.entity.MessageEntity;
import com.example.admin.goodnews.utils.GetCurrentTimeUtil;

import java.util.ArrayList;

import java.util.List;


/**
 * 聊天数据库管理者
 * Created by admin on 2016/10/21.
 */

public class ChatDBManager {

    private ChatDBHelper chatDBHelper;
    private SQLiteDatabase sqLiteDatabase;

    public ChatDBManager(ChatDBHelper chatDBHelper, SQLiteDatabase sqLiteDatabase) {
        this.chatDBHelper = chatDBHelper;
        this.sqLiteDatabase = sqLiteDatabase;
    }

    // 添加数据
    public void insertdata(String name, String message, int type) {
        sqLiteDatabase = chatDBHelper.getWritableDatabase();
        sqLiteDatabase.execSQL("insert into chat (name,message,type) values('" + name + "','" + message + "','" + type + "')");
        sqLiteDatabase.close();
    }

    // 查询消息数据
    public List<MessageEntity> querydata() {
        sqLiteDatabase = chatDBHelper.getWritableDatabase();
        //  order by id desc limit 0,2
        // rawQuery("select * from chat", null);
        Cursor cursor = sqLiteDatabase.rawQuery("select * from chat ", null);
        List<MessageEntity> chatlist = new ArrayList<>();
        while (cursor.moveToNext()) {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setId(cursor.getInt(cursor.getColumnIndex("id")));
            messageEntity.setName(cursor.getString(cursor.getColumnIndex("name")));
            messageEntity.setMessage(cursor.getString(cursor.getColumnIndex("message")));
            messageEntity.setType(cursor.getInt(cursor.getColumnIndex("type")));
            chatlist.add(messageEntity);
        }
        sqLiteDatabase.close();
        return chatlist;
    }
}
